/**
 * AES加解密模块
 * */
import CryptoJS from 'crypto-js'

class Crypto {
  constructor (key) {
    this.key = CryptoJS.enc.Utf8.parse(key)
  }
  // 加密
  encrypt (word) {
    var srcs = CryptoJS.enc.Utf8.parse(word)
    var encrypted = CryptoJS.AES.encrypt(srcs, this.key, { mode: CryptoJS.mode.ECB, padding: CryptoJS.pad.Pkcs7 })
    return encrypted.toString()
  }

  // 短名
  enc (word) {
    return this.encrypt(word)
  }

  // 解密
  decrypt (word) {
    var decrypt = CryptoJS.AES.decrypt(word, this.key, { mode: CryptoJS.mode.ECB, padding: CryptoJS.pad.Pkcs7 })
    return CryptoJS.enc.Utf8.stringify(decrypt).toString()
  }

  // 短名
  dec (word) {
    return this.decrypt(word)
  }

  /*
  * 加密对象(浅)
  * @param obj 处理对象
  * @param incKey 是否处理key
  */
  encryptObj (obj, incKey) {
    let encObj = {}
    Object.keys(obj).forEach(key => {
      if (incKey) {
        encObj[this.encrypt(key)] = this.encrypt(obj[key])
      } else {
        encObj[key] = this.encrypt(obj[key])
      }
    })
    return encObj
  }
  /*
  * 解密对象(浅)
  * @param obj 处理对象
  * @param incKey 是否处理key
  */
  decryptObj (obj, incKey) {
    let decObj = {}
    Object.keys(obj).forEach(key => {
      if (incKey) {
        decObj[this.encrypt(key)] = this.encrypt(obj[key])
      } else {
        decObj[key] = this.encrypt(obj[key])
      }
    })
    return decObj
  }
}

export default Crypto
